package cn.mrlong.mycalendar

import android.app.WallpaperManager
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.WindowManager
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.mrlong.mycalendar.databinding.ActivityMainBinding
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale


class MainActivity : AppCompatActivity() {
    private var recyclerView: RecyclerView? = null
    private var binding: ActivityMainBinding? = null

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
        window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER);
        initView()
        initData()
        initListener()
    }

    private fun initListener() {
        binding?.title?.let {
            it.tvNextMonth.setOnClickListener {
                calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + 1);
                updateAdapter(
                    calendar,
                    dataList,
                    binding?.recyclerView?.adapter as CalenderAdapter
                );
            }
            it.tvPreMonth.setOnClickListener {
                calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1);
                updateAdapter(
                    calendar,
                    dataList,
                    binding?.recyclerView?.adapter as CalenderAdapter
                );
            }
        }
    }

    private val calendar = Calendar.getInstance();

    @RequiresApi(Build.VERSION_CODES.O)
    private fun initData() {

        var manager: GridLayoutManager = GridLayoutManager(this, 7)
        var adapter: CalenderAdapter = CalenderAdapter(this, dataList)
        recyclerView?.let {
            it.adapter = adapter
            it.layoutManager = manager
        }

        setCurrentData(calendar);
        updateAdapter(calendar, dataList, adapter);
    }

    private var dataList: ArrayList<DayBean> = ArrayList<DayBean>()

    private fun updateAdapter(
        calendar: Calendar,
        dataList: MutableList<DayBean>,
        adapter: CalenderAdapter
    ) {
        dataList.clear()
        setCurrentData(calendar)
        // 得到本月一号的星期索引
        // 索引从 1 开始，第一个为星期日,减1是为了与星期对齐，如星期一对应索引1，星期二对应索引二
        calendar[Calendar.DAY_OF_MONTH] = 1
        var weekIndex = calendar[Calendar.DAY_OF_WEEK] - 1
        var lunarCalender = LunarCalender()

        // 将日期设为上个月
        calendar[Calendar.MONTH] = calendar[Calendar.MONTH] - 1
        val preMonthDays: Int = getMonth(
            calendar[Calendar.MONTH] + 1,
            calendar[Calendar.YEAR]
        )
        var day: Int? = null
        var month: Int? = null
        var year: Int? = null
        // 拿到上一个月的最后几天的天数
        for (i in 0 until weekIndex) {
            day = preMonthDays - weekIndex + i + 1
            month = calendar[Calendar.MONTH] + 1
            year = calendar[Calendar.YEAR]
            val bean = DayBean(
                day, month,
                year,
                lunarCalender.getLunarDate(year, month, day, false),
                lunarCalender.getyiji(year, month, day),
            )
            dataList.add(bean)
        }

        // 将日期设为当月
        calendar[Calendar.MONTH] = calendar[Calendar.MONTH] + 1
        val currentDays: Int = getMonth(
            calendar[Calendar.MONTH] + 1,
            calendar[Calendar.YEAR]
        )
        // 拿到当月的天数
        for (i in 0 until currentDays) {
            day = i + 1
            month = calendar[Calendar.MONTH] + 1
            year = calendar[Calendar.YEAR]
            val bean = DayBean(
                day, month, year,
                lunarCalender.getLunarDate(year, month, day, false),
                lunarCalender.getyiji(year, month, day),
            )
            // 当前日期
            val nowDate = getFormatTime("yyyy-M-d", Calendar.getInstance().time)
            // 选择的日期
            val selectDate = getFormatTime("yyyy-M-", calendar.time) + (i + 1)
            // 假如相等的话，那么就是今天的日期了
            if (nowDate.contentEquals(selectDate)) {
                bean.currentDay = (true)
            } else {
                bean.currentDay = (false)
            }
            bean.currentMount = (true)
            dataList.add(bean)
        }

        // 拿到下个月第一周的天数
        // 先拿到下个月第一天的星期索引
        // 之前设为了1号，所以将日历对象的月数加 1 就行了
        calendar[Calendar.MONTH] = calendar[Calendar.MONTH] + 1
        weekIndex = calendar[Calendar.DAY_OF_WEEK] - 1
        for (i in 0 until 7 - weekIndex) {
            day = i + 1
            month = calendar[Calendar.MONTH] + 1
            year = calendar[Calendar.YEAR]
            val bean = DayBean(
                i + 1,
                calendar[Calendar.MONTH] + 1,
                calendar[Calendar.YEAR],
                lunarCalender.getLunarDate(year, month, day, false),
                lunarCalender.getyiji(year, month, day),
            )
            bean.currentDay = (false)
            bean.currentMount = (false)
            dataList.add(bean)
        }
        adapter.notifyDataSetChanged()
        // 最后将日期设为当月
        calendar[Calendar.MONTH] = calendar[Calendar.MONTH] - 1
    }

    // 格式化时间，设置时间很方便，也比较简单，学的很快
    private fun getFormatTime(p: String?, t: Date?): String? {
        return SimpleDateFormat(p, Locale.CHINESE).format(t)
    }

    // 设置当前的时间
    private fun setCurrentData(calendar: Calendar) {
        binding?.let {
            it.title.tvCurrentDate.text =
                calendar[Calendar.YEAR].toString() + "年" + (calendar[Calendar.MONTH] + 1) + "月"
            it.currentMonth.text = getFormatTime("yyyy-MM-dd", Calendar.getInstance().time)
            it.currentMonth.setTextColor(Color.GRAY)
            it.currentMonth.alpha = 0.45f
        }
    }

    // 判断是否为闰年
    private fun isRunYear(y: Int): Boolean {
        return y % 4 == 0 && y % 100 != 0 || y % 400 == 0
    }

    private fun getMonth(m: Int, y: Int): Int {
        when (m) {
            2 -> {
                return if (isRunYear(y)) {
                    29
                } else {
                    28
                }
            }

            4, 6, 9, 11 -> {
                return 30
            }

            else -> {
                return 31
            }
        }
    }

    private fun initView() {
        recyclerView = binding!!.recyclerView
    }
}